package battle.map
{
	import flash.display.BitmapData;
	import flash.geom.Rectangle;
	import flash.utils.Dictionary;

	public class Tile
	{
		public var tileId:String;
		
		public var tilesetName:String;
		
		public var tileIndex:int;
		
		//public var tileImg:BitmapData;
		
		protected var rect:Rectangle;
		
		protected static var tiles:Dictionary = new Dictionary();;
		
		public function Tile()
		{
		}
		
		public static function newTile( tileId:String ):Tile
		{
			
			var tile:Tile = tiles[tileId];
			
			if( tile == null )
			{
				tile =  new Tile();
			
				tiles[ tileId ] = tile;
			
				//相关初始化
				tile.tileId = tileId;
				
				//var tileIndex:int = 0;
				
				tile.tilesetName = "";
				
				tile.tileId.replace( /([a-zA-Z]*)([0-9]+)/, function(){
								
								tile.tileIndex = arguments[2];
								tile.tilesetName = arguments[1];
								
								return "";
						}
				);
				
				
				
			}
			
			return tile;
		}

		
		public function getRect():Rectangle
		{
			if( rect == null )
			{
				var bitmapData:BitmapData = Tileset.getTilesetBitmap( this.tilesetName );
				
				if( bitmapData != null )
				{
					
					var totalCol:int = bitmapData.width / Map.TILE_WIDTH;
					
					var row:int = tileIndex / totalCol;
					
					var col:int = tileIndex % totalCol;
					
					this.rect = new Rectangle( col * Map.TILE_WIDTH, row * Map.TILE_HEIGHT, Map.TILE_WIDTH, Map.TILE_HEIGHT );
				}
			}
			
			return rect;
		}
		
	}
}